<template>
  <div class="refine_importarea">
    <h2 class="titleblue">重点区域</h2>
    <el-row :gutter="20">
      <el-col :span="6" class="shipli" v-for="(item,index) in shipgroup" :key="index">
        <div class="grid-content bg-purple" :id="'mapid'+item.d_id">
          <!-- <img :src="item.src"> -->
          <div class="attention" @click="attention(item.d_id)">取消关注</div>
          <div class="shipbtn" @click='qiehuan(item.lat,item.lon)'>切换</div>
        </div>
        <p>{{item.name}}</p>
      </el-col>
    </el-row>
    <el-dialog
      title=""
      :visible.sync="dialogDelete"
      width="30%"
      class="dialogDelete"
      append-to-body
      center>
      <span>确定要取消关注？</span>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogDelete = false">取 消</el-button>
        <el-button type="primary" @click="suredel">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import * as keyAreaService from '@/services/KeyAreaService'

  export default {
    props: ['ddd'],
    data: function () {
      return {
        id: '',
        deleteData: [],
        dialogDelete: false,
        length: 0,
        prevTime: 0,
        prevDraw: 0,
        prevRdraw: 0,
        hoverPg: null,
        cli: '',
        showGrids: null,
        mytiles: {},
        shipgroup: [
          {

            attention: '取消关注',
            name: '重点区域1'
          }
        ],
        shipIcons: [],
        reqNow: false,
        values: undefined,
        marks: {},
        lg: {},
      };
    },
    watch: {
      ddd(oldval, newval) {
        if (oldval != newval) {
          this.getData()
        }
      }
    },
    mounted() {
      this.getData()
    },
    methods: {
      getKeyArea() {
        let userId = this.$profile.id;
        return keyAreaService.search(userId);
      },
      getData() {
        this.shipgroup = [];
        this.getKeyArea().then((retlist) => {
          for (let k = 0; k < retlist.length; k++) {
            let oneobj = {};
            oneobj.d_id = retlist[k].id;
            oneobj.lat = retlist[k].latitude;
            oneobj.lon = retlist[k].longitude;
            oneobj.name = retlist[k].name;
            this.shipgroup.push(oneobj);
          }
        }).then(() => {
          this.generateMap();
        });
      },
      reDraw(map) {
        var level = map.getZoom();
        this.cli.tileCoord.setLevel(level);
        if (level <= 10) {
          return;
        }
        var bounds = map.getBounds();
        var minx = OurNav.normalizeLon(bounds.getWest());
        var maxx = OurNav.normalizeLon(bounds.getEast());
        var miny = bounds.getSouth();
        var maxy = bounds.getNorth();

        var lt = this.cli.merc.forward(minx, maxy);
        var rb = this.cli.merc.forward(maxx, miny);

        var rcTile = new OurNav.Rect(0, 0, 0, 0);
        this.cli.tileCoord.fromMerc(lt);
        rcTile.minx = this.cli.tileCoord.col;
        rcTile.miny = this.cli.tileCoord.row;
        this.cli.tileCoord.fromMerc(rb);
        rcTile.maxx = this.cli.tileCoord.col;
        rcTile.maxy = this.cli.tileCoord.row;

        for (var x = rcTile.minx; x <= rcTile.maxx; x++) {
          for (var y = rcTile.miny; y <= rcTile.maxy; y++) {
            var key = x + "," + y + "," + level;
            var tile = this.cli.cachedTiles[key];
            if (tile) {
              OurNav.drawTile(tile, this.cli, y, x);
            }
          }
        }
        OurNav.removeWhenTooMany(this.cli);
      },
      updateData(map) {
        var level = map.getZoom();
        if (level <= 10) {
          return;
        }
        var bounds = map.getBounds();
        var minx = bounds.getWest();
        var maxx = bounds.getEast();
        var miny = bounds.getSouth();
        var maxy = bounds.getNorth();

        var to = OurNav.encodeBounds(minx, miny, maxx, maxy, this.cli, msgpack);

        if (!to) {
          return;
        }
        if (oReq) {
          oReq.abort();
          oReq = null;
        }
        var oReq = new XMLHttpRequest();
        oReq.open("POST", this.$config.SHIP_BOUNDS_URL, true);
        oReq.responseType = "arraybuffer";
        oReq.onload = (oEvent) => {
          var blob = oReq.response;
          var byteArray = new Uint8Array(blob);
          var data = msgpack.decode(byteArray);
          if (data) {

            OurNav.updateGrids(data, this.cli);
          }
          oReq = null;
        };
        if (oReq) {
          oReq.send(to);
        }
      },
      time(map) {
        if ((new Date()).getTime() - this.prevTime >= 2000) {
          this.updateData(map);
          this.prevTime = (new Date()).getTime();
        }
        if ((new Date()).getTime() - this.prevDraw >= 200) {
          this.reDraw(map);
          this.prevDraw = (new Date()).getTime();
        }
        setTimeout(() => {
          this.time(map)
        }, 30);
      },
      attention(id) {
        this.dialogDelete = true
        this.id = id
      },
      qiehuan(lat, lon) {
        var dgree = [lat, lon]
        this.$emit('qiehuan', dgree)
      },
      async suredel() {
        let retobj = await keyAreaService.deleteById(this.id);
        this.dialogDelete = false;
        this.getData();
      },
      generateMap() {
        for (let i = 0; i < this.shipgroup.length; i++) {
          this.shipgroup[i].map = new L.Map('mapid' + this.shipgroup[i].d_id, {
            fullscreenControl: false,
            fullscreenControlOptions: {
              position: 'topleft'
            },
            zoominfoControl: false,
            zoomControl: false,
            attributionControl: false
          });
          // var osmUrl= this.$config['outw']+'/{z}/{x}/{y}';
          //var osmUrl = this.$config['innw'] + '/{z}/{x}/{y}';
          var osmAttrib = 'Map data &copy; 国交信通 contributors';
          var osm = new L.TileLayer(this.$config.OSM_URL, {minZoom: 1, maxZoom: 18, attribution: osmAttrib});

          //船位瓦片
          // var shipUrl=this.$config['outship']+'/{z}/{x}/{y}';
          //var shipUrl = this.$config['inship'] + '/{z}/{x}/{y}';
          var shipTile = new L.TileLayer(this.$config.SHIP_URL, {minZoom: 1, maxZoom: 10});

          this.shipgroup[i].map.addLayer(osm);
          this.shipgroup[i].map.addLayer(shipTile);
          this.shipgroup[i].map.setView(new L.LatLng(this.shipgroup[i].lat, this.shipgroup[i].lon), 9)

          //船位服务
          var tiles = new L.GridLayer({
            minZoom: 0,
            maxZoom: 18
          });

          this.cli = new OurNav.LBSClient();
          this.cli.lostTime = 30 * 24 * 3600;
          var _self = this
          tiles.createTile = function (coords) {
            var tile = L.DomUtil.create('canvas', 'leaflet-tile');
            tile.version = 0;
            var size = this.getTileSize();
            tile.width = size.x
            tile.height = size.y
            tile.col = coords.x;
            tile.row = coords.y;
            tile.level = coords.z;
            _self.cli.cachedTiles[_self.cli.getTileKey(coords)] = tile;
            return tile;
          }
          tiles.addTo(this.shipgroup[i].map)
          tiles.on("tileunload", (e) => {
            delete this.cli.cachedTiles[this.cli.getTileKey(e.coords)];
          });

          this.shipgroup[i].map.on("moveend", (e) => {
            this.prevTime = 0;
            this.prevDraw = 0;
          });

          this.shipgroup[i].map.on("zoomend", (e) => {
            this.prevTime = 0;
            this.prevDraw = 0;
            this.time(e.target)
          });

          this.shipgroup[i].map.on("movestart", (e) => {
            this.prevDraw = (new Date()).getTime();
          });

          this.shipgroup[i].map.on("zoomstart", (e) => {
            this.prevDraw = (new Date()).getTime();
            if (this.hoverPg) {
              this.hoverPg.remove();
              this.hoverPg = null;
            }
          });

          this.shipgroup[i].map.on("move", (e) => {
            this.prevDraw = (new Date()).getTime();
          });

          this.shipgroup[i].map.on("zoom", (e) => {
            this.prevDraw = (new Date()).getTime();
          });
          this.shipgroup[i].map.on("mousemove", (e) => {
            var pt = e.latlng;
            var lng = OurNav.normalizeLon(pt.lng);
            var lng_off = pt.lng - lng;
            var latlngs = null;
            var label = null;
            pt = this.cli.merc.forward(lng, pt.lat);
            this.cli.tileCoord.fromMerc(pt);
            var keys = Object.keys(this.cli.shipDraws);
            for (var i = keys.length - 1; i >= 0; i--) {
              var sd = this.cli.shipDraws[keys[i]];
              if (sd && sd.shape) {
                if (sd.shape.contains(this.cli) && sd.shape.hitTest(this.cli, true)) {
                  latlngs = sd.shape.toLatLngs(this.cli);
                  var date = new Date(sd.last_time * 1000);
                  label = "<b><center>" + sd.getLabel() + "</center></b>";
                  label += "<hr>";
                  label += "<font color='#483D8B'>标识代码：</font>" + sd.id;
                  if (sd.length > 0 && sd.width > 0) {
                    label += "<br>" + "<font color='#483D8B'>船舶尺寸：</font>" + sd.length + " × " + sd.width;
                  }
                  var speed = sd.sog * 3600 / 1852.0;
                  speed = Math.round(speed * 100) / 100;
                  label += "<br>" + "<font color='#483D8B'>船舶速度：</font>" + speed + "节";
                  label += "<br>" + "<font color='#483D8B'>最后时间：</font>" + date.pattern("yyyy-MM-dd hh:mm:ss");
                  break;
                }
              }
            }

            if (this.hoverPg) {
              this.hoverPg.remove();
              this.hoverPg = null;
            }
            if (latlngs && lng_off != 0) {
              for (var i = 0; i < latlngs.length; i++) {
                latlngs[i][1] += lng_off;
              }
            }
            if (latlngs) {
              this.hoverPg = L.polygon(latlngs, {
                color: 'red',
                weight: 1.0,
                smoothFactor: 0.5
              });
              if (this.hoverPg) {
                this.hoverPg.addTo(e.target);
                if (label) {
                  this.hoverPg.bindTooltip(label, {
                    permanent: true,
                    direction: 'right',
                    offset: [20, 0]
                  });
                }
              }
            }
          })
        }
        this.length = this.shipgroup.length;
      }

    }
  };

</script>

<style scoped>
  @import '../../../../static/css/leaflet.css';
  @import '../../../../static/css/Control.FullScreen.css';
</style>
<style lang='scss'>
  .refine_importarea {
    box-sizing: border-box;
    overflow-x: hidden;

    .el-row {
      padding: 30px;
    }
    .grid-content {
      width: 100%;
      position: relative;
      height: 200px;
    }

    .attention {
      position: absolute;
      right: 0;
      top: 0;
      z-index: 1000;
      cursor: pointer;
      background-color: #0062cd;
      color: #fff;
      font-size: 14px;
      padding: 3px 20px;
    }
    .shipbtn {
      position: absolute;
      left: 0px;
      top: 0px;
      z-index: 1000;
      cursor: pointer;
      background-color: #0062cd;
      color: #fff;
      font-size: 14px;
      padding: 3px 8px;
    }
    .el-row p {
      font-size: 16px;
      color: #333333;
      text-align: center;
      line-height: 40px;
      margin-bottom: 10px;
    }
    .dialogDelete span {
      width: 100%;
      display: inline-block;
      text-align: center;
    }
    .border-dot .grid-content {
      height: 200px;
      border: dashed 1px #d6d6d6;
      display: block;
      text-align: center;
      line-height: 200px;
      vertical-align: middle;
    }
    .border-dot .grid-content img {
      vertical-align: middle;
      width: auto;
      height: auto;
    }
  }
</style>
